package com.huajx.core.udp;

import com.huajx.core.log.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;

/**
 * @program: di-parent
 * @description:
 * @author: lisa 叶新华
 * @create: 2019-09-17 14:13
 */
public class LocalUDPSocketProvider {
    private static final String TAG = LocalUDPSocketProvider.class.getSimpleName();
    private static final Logger logger = LoggerFactory.getLogger(TAG);
    private static LocalUDPSocketProvider instance = null;
    private MulticastSocket localUDPSocket = null;

    public static LocalUDPSocketProvider getInstance() {
        if (instance == null)
            instance = new LocalUDPSocketProvider();
        return instance;
    }

    public void initSocket(String serverIP, int serverUDPPort, int localUDPPort) {
        try {
            // UDP本地监听端口（如果为0将表示由系统分配，否则使用指定端口）
            this.localUDPSocket = new MulticastSocket(localUDPPort);
            // 调用connect之后，每次send时DatagramPacket就不需要设计目标主机的ip和port了
            // * 注意：connect方法一定要在DatagramSocket.receive()方法之前调用，
            // * 不然整send数据将会被错误地阻塞。这或许是官方API的bug，也或许是调
            // * 用规范就应该这样，但没有找到官方明确的说明
            this.localUDPSocket.joinGroup(InetAddress.getByName(serverIP));
//            this.localUDPSocket.connect(
//                    InetAddress.getByName(serverIP), serverUDPPort);
//            this.localUDPSocket.setReuseAddress(true);
            Log.d(TAG, "new DatagramSocket()已成功完成.");
        } catch (Exception e) {
            Log.w(TAG, "localUDPSocket创建时出错，原因是：" + e.getMessage(), e);
        }
    }

    public DatagramSocket getLocalUDPSocket() {
        return this.localUDPSocket;
    }
}
